<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'import_excel'" type="danger" size="small" @click="exportExce">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table :default-sort="{prop: 'timeOfEntry', order: 'descending'}" :data="list" border>
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <!-- 显示员工的头像 -->
          <el-table-column label="头像" width="100">
            <template #default="{row}">
              <img
                :src="row.staffPhoto"
                style="width:100%"
                @imgerror="require('@/assets/common/bigUserHeader.png')"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/detail?userId=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-size="size"
            layout="prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <empDialog v-if="showDialog" @can="showDialog=false" @success="hSuccess" />
      </el-dialog>
      <el-dialog
        title="分配角色"
        :visible.sync="showDialogRole"
      ><AssignRole v-if="showDialogRole" :cur-id="curId" @success="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import empDialog from '@/views/employees/empDialog.vue'
import { getEmployees, delEmployees } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import AssignRole from './assignRole'
// const hireType = {}
// EmployeeEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
const hireType = EmployeeEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    empDialog,
    AssignRole
  },
  data() {
    return {
      curId: '',
      showDialogRole: false, // 控制分配角色的弹层
      showDialog: false, // 控制弹框的显示和隐藏
      list: [],
      page: 1, // 页码值
      size: 5, // 每页显示的数据
      total: 0
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    hAssignRole(id) {
      this.showDialogRole = true
      this.curId = id
    },
    exportExce() {
      const { tHeader, data } = this.TransZhKeyToExcel(this.list)
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    TransZhKeyToExcel(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map(item => {
        return mapInfo[item]
      })
      const data = list.map(item => {
        return Object.values(item)
      })
      return { tHeader, data }
    },
    // 删除角色
    hDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployees(id)
        if (res.code === 10000) {
          this.$message.success(res.message)
          // 边界判断
          if (this.list.length === 1) {
            this.pageParams.page--
            if (this.pageParams.page <= 0) {
              this.page = 1
            }
          }
          this.loadEmployees()
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      // 将页码翻到最后一页
      this.page = maxPage
      this.showDialog = false
      this.loadEmployees()
    },
    // 当前页码值切换时触发
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    // 格式化数据函数
    formatData(id) {
      // return EmployeeEnum.hireType.find(item => item.id === id).value
      return hireType[id] || '未知'
    },
    // 渲染数据
    async loadEmployees() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size })
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
